<style scoped lang="scss">
.page{width: 100%;height: 100%;}
.outer{width: 100%;height: 100%;justify-content: center;position: relative;}
.video-outer{width: 200px;height: 200px;overflow: hidden;border-radius: 50%;
  .video{width: 100%;height: 100%;}
}
.buttons{position: absolute;left: 0;bottom: 0;padding-bottom: 50px;text-align: center;width: 100%;}

</style>
<template>
  <div class="page">
    <div class="outer flex">
      <div class="video-outer">
        <video v-show="stream" ref="video" class="video" src="" ></video>
      </div>

      <div class="buttons">
        <van-button v-if="playing" :type="'danger'" @click="stopCamera">关闭摄像头</van-button>
        <van-button v-else :type="'primary'" @click="startCamera">开启摄像头</van-button>
      </div>
    </div>
  </div>
</template>

<script>

import {alert} from "@/js/vant_tool.js";

async function getUserMedia(width, height, facingMode='user', audio=false){
  // 旧版API兼容模式
  navigator.getUserMedia = navigator.getUserMedia ||
      navigator.webkitGetUserMedia ||
      navigator.mozGetUserMedia ||
      navigator.msGetUserMedia;

  // 检查支持情况
  if (!navigator.mediaDevices.getUserMedia && !navigator.getUserMedia) {
    throw new Error('不支持摄像头功能');
  }
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    return await navigator.mediaDevices.getUserMedia({
      video: {
        facingMode: facingMode, // 前置摄像头
        width: { ideal: width },
        height: { ideal: height }
      },
      audio: audio
    });
  } else {
    return await new Promise((resolve, reject) => {
      navigator.getUserMedia({
        video: {
          facingMode: facingMode, // 前置摄像头
          width: width,
          height: height
        },
        audio: audio
      }, resolve, reject);
    });
  }
}

/**
 * @prop {*}
 */
export default {
  _title_: '测试摄像头',
  props:{},
  data(){
    return {
      stream: null,
      playing: false,
    }
  },
  methods:{
    async startCamera() {
      try {
        // 请求摄像头权限
        this.stream = await getUserMedia(720, 720);

        // 将媒体流连接到video元素
        this.$refs.video.srcObject = this.stream;

        // 播放视频
        await this.$refs.video.play();
        this.playing = true;

        console.log('摄像头已开启');

      } catch (error) {
        console.error('无法访问摄像头:', error);
        alert('无法访问摄像头: ' + error.message);
      }
    },
    stopCamera() {
      if (this.stream) {
        // 停止所有轨道
        this.stream.getTracks().forEach(track => {
          track.stop();
        });

        // 清空video源
        this.$refs.video.srcObject = null;
        this.playing = false;
      }
    },

  },
  computed:{},
  mounted(){
    this.startCamera();
  }
}
</script>